package com.example.demo.interceptors;

import com.example.demo.utils.JwtUtils;
import com.example.demo.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

import static com.example.demo.config.SelfFinalProperty.USER_ID;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //令牌验证
        String token = request.getHeader("Authorization");
        try {
            //1.校验token
            //1.1校验token是否被篡改或过期
            if(!JwtUtils.verifyToken(token)){
                //token已过期
                log.info("token已过期--1");
                throw new RuntimeException("token已过期--1");
            }
            //2.解析token
            Map<String, Object> user = JwtUtils.getUserOfToken(token);
            //1.2校验redis中token是否过期
            if (!token.equals(redisTemplate.opsForValue().get(USER_ID+user.get("id")))){
                log.info("token已过期--2");
                throw new RuntimeException("token已过期--2");
            }

            //3.解析的user存储到ThreadLocal中
            ThreadLocalUtil.set(user);
            //4.放行
            log.info("拦截器放行了");
            return true;
        } catch (Exception e) {
            response.setStatus(401);
            //不放行
            log.info("拦截器没有放行");
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清空ThreadLocal中的数据
        ThreadLocalUtil.remove();
    }
}
